<script setup lang="ts">
import { NModal, useMessage, NInput, NButton } from 'naive-ui'
import { sendRequest } from '@/utils/api'
import { ref, computed } from 'vue'

import VDialogContent from '@/views/OA/Common/DialogContent.vue'

const props = defineProps<{
  ids?: string[] | null
}>()

const emit = defineEmits<{
  (event: 'refresh'): void
}>()

enum Action {
  AGREE = '同意',
  REJECT = '拒绝'
}

const message = useMessage()
const modalVisible = ref(false)
const resultFlag = ref(false)
const opinions = ref('')
const actionDisabled = computed(() => submitLoading.value || !props.ids || !props.ids.length)

const handleAction = (action: Action) => {
  opinions.value = action
  resultFlag.value = action === Action.AGREE
  modalVisible.value = true
}

const submitLoading = ref(false)
const handleSubmit = async () => {
  submitLoading.value = true
  try {
    const [error, res] = await sendRequest({
      module: 'userCenter',
      api: 'emaineDispose',
      override: {
        data: {
          resultFlag: resultFlag.value,
          opinions: opinions.value,
          fromId: props.ids!.join(',')
        }
      }
    })
    if (error) throw new Error(error.message)
    if (res.code !== 0) throw new Error(res.msg)
    message.success('操作成功')
    modalVisible.value = false
    document.dispatchEvent(new Event('flushTopCount'))
    emit('refresh')
  } catch (error) {
    if (error instanceof Error) message.error(error.message)
  } finally {
    submitLoading.value = false
  }
}
</script>

<template>
  <div class="batch-audit">
    <NButton
      type="primary"
      @click="handleAction(Action.AGREE)"
      :disabled="actionDisabled"
      ghost
    >
      批量编目审核同意
    </NButton>
    <NButton
      type="error"
      @click="handleAction(Action.REJECT)"
      :disabled="actionDisabled"
      ghost
    >
      批量编目审核拒绝
    </NButton>
  </div>

  <NModal
    :auto-focus="false"
    v-model:show="modalVisible"
    @close="modalVisible = false"
  >
    <VDialogContent
      @close="modalVisible = false"
      @submit="handleSubmit"
      title="审核"
    >
      <div style="display: flex">
        备注:
        <NInput
          v-model:value="opinions"
          placeholder="请输入备注"
          type="textarea"
          style="width: 400rem; height: 200rem; margin-left: 10rem"
        />
      </div>
    </VDialogContent>
  </NModal>
</template>

<style scoped>
.batch-audit {
  display: inline-flex;
  align-items: center;
  gap: 0 20rem;
}
</style>
